package com.lzm.ydpt;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.basemvp.BasePresenter;
import com.byt.framlib.commonutils.SharePerUtils;
import com.example.message.R;
import com.example.message.dto.BaseDto;
import com.example.message.dto.LoginDto;
import com.example.message.http.Api;
import com.example.message.view.ClearEditText;
import com.example.message.vo.UserVo;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.lzm.ydpt.module.common.WelActivity;
import com.lzmpt.imchat.DemoApplication;
import com.lzmpt.imchat.DemoHelper;
import com.lzmpt.imchat.db.DemoDBManager;
import com.lzmpt.imchat.ui.MainActivity;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    private RelativeLayout rlCancel;
    private ClearEditText etPhone;
    private ClearEditText etPwd;
    private RelativeLayout rlEye;
    private ImageView ivEye;

    private TextView tvLoginForgetPwd;
    private TextView tvLogin;
    private TextView tvCreatUser;
    private ImageView ivWeixin;
    private ImageView ivQq;
    private ImageView ivWeibo;


    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public BasePresenter initPreData() {
        return null;
    }

    private boolean mbDisplayFlg;
    private int loginType = 1;

    @Override
    public void initView() {
        rlCancel = (RelativeLayout) findViewById(R.id.rl_cancel);
        etPhone = (ClearEditText) findViewById(R.id.et_phone);
        etPwd = (ClearEditText) findViewById(R.id.et_pwd);
        rlEye = (RelativeLayout) findViewById(R.id.rl_eye);
        ivEye = (ImageView) findViewById(R.id.iv_eye);

        tvLoginForgetPwd = (TextView) findViewById(R.id.tv_login_forget_pwd);
        tvLogin = (TextView) findViewById(R.id.tv_login);
        tvCreatUser = (TextView) findViewById(R.id.tv_creat_user);
        ivWeixin = (ImageView) findViewById(R.id.iv_weixin);
        ivQq = (ImageView) findViewById(R.id.iv_qq);
        ivWeibo = (ImageView) findViewById(R.id.iv_weibo);

        tvCreatUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        });
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        rlEye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mbDisplayFlg) {
                    // display password text, for example "123456"
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    ivEye.setImageResource(R.drawable.image_login_open);
                } else {
                    // hide password, display "."
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    ivEye.setImageResource(R.drawable.image_login_close);
                }
                etPwd.setSelection(etPwd.getText().toString().length());//将光标移至文字末尾
                mbDisplayFlg = !mbDisplayFlg;
                etPwd.postInvalidate();

            }
        });
        rlCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private boolean progressShow;

    /**
     * login
     *
     * @param
     */
    public void login() {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }
        final String currentUsername = etPhone.getText().toString().trim();
        final String currentPassword = etPwd.getText().toString().trim();

        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(currentPassword)) {
            Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        progressShow = true;
        final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                Log.d(TAG, "EMClient.getInstance().onCancel");
                progressShow = false;
            }
        });
        pd.setMessage(getString(R.string.Is_landing));
        pd.show();
        UserVo vo = new UserVo();
        vo.setUsername(currentUsername);
        vo.setPassword(currentPassword);

        Api.login(vo).
                subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Subscriber<BaseDto<List<LoginDto>>>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(100);
                    }

                    @Override
                    public void onNext(BaseDto<List<LoginDto>> baseDto) {

                        if (baseDto.getCode()==200) {
                            Log.e(TAG, "onNext: 登录服务器成功");

                            imLogin(currentUsername, currentPassword, baseDto.getData().get(0),pd);
                        } else {
                            Log.e(TAG, "onNext: 登录服务器失败" + baseDto.getMessage());
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(), baseDto.getMessage(), Toast.LENGTH_SHORT).show();
                        }


                    }

                    @Override
                    public void onError(Throwable t) {
                        Log.e(TAG, "onNext: 登录服务器失败" + t.getMessage());
                        Toast.makeText(getApplicationContext(), "注册失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                        pd.dismiss();
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    private void imLogin(final String currentUsername, final String currentPassword, final LoginDto dto, final ProgressDialog pd) {
        Log.e(TAG, "onNext: 正在登陆im");
        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(currentUsername);

        final long start = System.currentTimeMillis();
        // call login method
        Log.d(TAG, "EMClient.getInstance().login");
        EMClient.getInstance().login(currentUsername, currentPassword, new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.d(TAG, "login: onSuccess");

                SharePerUtils.setSharedString("token",dto.getToken());


                // ** manually load all local groups and conversation
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(
                        DemoApplication.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }

                if (!LoginActivity.this.isFinishing() && pd.isShowing()) {
                    pd.dismiss();
                }

                // get user's info (this should be get from App's server or 3rd party service)
                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

                goToMain();
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d(TAG, "login: onProgress");
            }

            @Override
            public void onError(final int code, final String message) {
                Log.d(TAG, "login: onError: " + code);
                if (!progressShow) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void goToMain() {

        startActivity(new Intent(LoginActivity.this, WelActivity.class));
        finish();

    }


}
